<template>
  <Card>
    <Api ref="apiRef" :load="pageDict" v-slot="{ input }">
      <Space direction="vertical">
        <Cond>
          <CondItem title="关键字" field="keyword">
            <Input v-model="input.params.keyword" placeholder="名称/字典码" />
          </CondItem>
          <template #op>
            <Button type="primary" @click="onCreate">
              <IconPlus />
            </Button>
          </template>
        </Cond>
        <Table :loadMore="loadMore">
          <TableColumn title="名称" field="name">
            <template #cell="{ row }">
              <Popover position="right">
                <Button is-text :text="row.name" />
                <template #content>
                  <Space>
                    <Button @click="onCreate({ pid: row.id })" text="创建子级" />
                    <Button @click="onUpdate(row)" text="编辑" />
                    <Button @click="onDelete(row.id)" v-text="'删除'" />
                  </Space>
                </template>
              </Popover>
            </template>
          </TableColumn>
          <TableColumn title="id" field="id" />
          <TableColumn title="字典至" field="value" />
          <TableColumn title="备注" field="remark" />
          <TableColumn title="英文" field="nameEn" />
          <TableColumn title="排序" field="sort" />
          <TableColumn title="创建日期" :width="120" field="createdAt" type="Date" />
          <TableColumn title="更新日期" :width="120" field="updatedAt" type="Date" />
        </Table>
      </Space>
    </Api>
  </Card>
</template>

<script setup>
import { Button, Space, Card, Cond, CondItem, Input, Popover, Table, TableColumn } from '@idmy/ui'
import { IconPlus } from '@idmy/ui-icon'
import { deleteDict, findChildrenDict, pageDict } from './services'
import { Api, useDelete } from '@idmy/core'
import { ref } from 'vue'
import { DictCreate } from '@/components/Sys/Dict/Create/index'

const apiRef = ref()
const onLoad = () => apiRef.value.onLoad()

const onCreate = (model = {}) =>
  Modal.open({
    component: DictCreate,
    title: '创建字典',
    enableLock: true,
    props: {
      model,
    },
    onClose: isOk => isOk && onLoad(),
  })

const onUpdate = (row = {}) =>
  Modal.open({
    component: DictCreate,
    title: '修改字典',
    props: {
      model: row,
    },
    onClose: isOk => isOk && onLoad(),
  })

const loadMore = (row, done) => {
  return findChildrenDict(row.id).then(done)
}
const onDelete = useDelete(deleteDict, onLoad)
</script>
